import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 选择排序
 * User: 86183
 * Date: 2023-04-24
 * Time: 10:08
 */
public class sortDeom3 {
    public static void main(String[] args) {
        int[] a = {99,67,34,12,3,4};
//        selectSort(a);
        selectSort1(a);
        System.out.println(Arrays.toString(a));
    }
    //进阶版
    private static void selectSort1(int[] a) {
        int l = 0;
        int r = a.length - 1;
        while (l < r ){
            int min = l;
            int max = l;
            for (int i = l+1; i <= r; i++) {
                if(a[i] < a[min]){
                    min = i;
                }
                if(a[i] > a[max]){
                    max = i;
                }
            }
            swap(a,l,min);
            //如果max下标正好是l说明上次,已经把最大值从l位置换到了min的位置
            if(l == max){
                max = min;
            }
            swap(a,r,max);
            l++;
            r--;
        }
    }

    private static void selectSort(int[] a) {
        for (int i = 0; i < a.length; i++) {
            int minindex = i;
            for (int j = i + 1; j <a.length; j++) {
                if(a[j] < a[minindex]){
                    minindex = j;
                }
            }
            if (minindex != i) {
                swap(a,i,minindex);
            }
        }
    }

    private static void swap(int[] a, int i, int minindex) {
        int tmp = a[i];
        a[i] = a[minindex];
        a[minindex] = tmp;
    }
    
}
